import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {
  NzCheckboxModule,
  NzCheckBoxOptionInterface,
} from 'ng-zorro-antd/checkbox';

@Component({
  selector: 'app-checkbox-group-all',
  standalone: true,
  imports: [NzCheckboxModule, FormsModule],
  template: `<div class="demo">
    <label
      nz-checkbox
      [ngModel]="isAllSelected"
      (ngModelChange)="handleSelectAll($event)"
      [nzIndeterminate]="indeterminate"
      >全选</label
    >
    <nz-checkbox-group
      [(ngModel)]="options"
      (ngModelChange)="handleSelectItem()"
    />
  </div> `,
  styles: ``,
})
export class CheckboxGroupAllComponent implements OnInit {
  private _isAllSelected = false;
  public get isAllSelected() {
    return this._isAllSelected;
  }

  private _indeterminate = false;
  public get indeterminate() {
    return this._indeterminate;
  }

  options: NzCheckBoxOptionInterface[] = [
    { label: '选项一', value: '1', checked: true },
    { label: '选项二', value: '2' },
    { label: '选项三', value: '3' },
    { label: '选项四', value: '4' },
  ];

  ngOnInit(): void {
    this.updateSelectAllState();
  }

  handleSelectAll(checked: boolean): void {
    this.options = this.options.map((item) => ({ ...item, checked: checked }));
    this.updateSelectAllState();
  }

  handleSelectItem(): void {
    this.updateSelectAllState();
  }

  private updateSelectAllState() {
    this._isAllSelected = this.options.every((item) => item.checked);
    this._indeterminate =
      this.options.some((item) => item.checked) && !this._isAllSelected;
  }
}
